package com.vframework.rest.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import com.vframework.common.constant.GlobalConstant;
import com.vframework.common.model.RegionsBean;
import com.vframework.rest.common.RestResponse;

@Service
public class RegionService {
    
    @SuppressWarnings("unchecked")
	public RestResponse listAllAreaAsTree() throws Exception {
	    Map result = new HashMap();
	    //从缓存GlobalConstant去CITY_LIST数据
	    List<RegionsBean> areaList = GlobalConstant.CITY_LIST;
	    //将CITY_LIST对象BaseBean转成RegionBean 并将RegionBean放入map
	    List<RegionsBean> regionList = new ArrayList<RegionsBean>();
	    List<RegionsBean> provinceList = new ArrayList<RegionsBean>();
	    Map<String, List<RegionsBean>> map = new HashMap<String, List<RegionsBean>>();
	    for (RegionsBean area : areaList) {
	        RegionsBean regionBean = new RegionsBean();
	        BeanUtils.copyProperties(regionBean, area);
	        regionBean.setChildren(new ArrayList<RegionsBean>());
	        regionList.add(regionBean);
	        if ("0".equals(area.getPcode())) {
	            provinceList.add(regionBean);
	        }
	        if (map.get(area.getPcode()) == null) {
	            List<RegionsBean> regions = new ArrayList<RegionsBean>();
	            regions.add(regionBean);
	            map.put(area.getPcode(), regions);
	        } else {
	            map.get(area.getPcode()).add(regionBean);
	        }
	    }
	    
	    for (RegionsBean regionBean: provinceList) {
	        //市
	        regionBean.setChildren(map.get(regionBean.getCode()));
	        //区
	        if (regionBean.getChildren() != null) {
	            for (RegionsBean city: regionBean.getChildren()) {
	                city.setChildren(map.get(city.getCode()));
	            }
	        }
	    }
	    result.put("regions", provinceList);
	    return new RestResponse(result);
	}
}
